package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/17
 * Time:14:44
 **/
public class Server {
    /**
     * 服务器端-"智能"聊天机器人
     */
    //端口号：
    private static final int port = 1001;
    //数据的最大值
    private static final int blen = 1024;

    public static void main(String[] args) throws IOException {
        //1.启动服务器端
        DatagramSocket socket = new DatagramSocket(port);
        System.out.println("服务器端已启动！");
        //循环输入
        while (true) {
            //2.初始化数据包
            DatagramPacket clientPacket = new DatagramPacket(new byte[blen], blen);
            //3.等待客户端连接
            socket.receive(clientPacket);
            System.out.println("连接客户端成功！");
            //4.接收客户端消息
            String msg = new String(clientPacket.getData());
            System.out.println("接收到：" + msg);
            //5.给客户端响应
            String serMsg = msg.replace("吗？", "!");
            //6.发送
            DatagramPacket serverPacket = new DatagramPacket(
                    serMsg.getBytes(),
                    serMsg.getBytes().length,
                    clientPacket.getAddress(),
                    clientPacket.getPort()
            );
            socket.send(serverPacket);
        }
    }

}
